import { Component, OnInit } from '@angular/core';
import { BaseInputComponent } from '@shared/base-form/base-input/base-input.component';

@Component({
  selector: 'base-json-array-input',
  templateUrl: './base-json-array-input.component.html',
})
export class BaseJsonArrayInputComponent extends BaseInputComponent implements OnInit {

  // READEME: 配置值格式必须为：
    /*  [{
        "key": "22222222222299",
        "value": "业绩高合金钢盒，及直规划局户15人"
      }, {
        "key": "11111111111111",
        "value": "自阿斯蒂芬盒"
      }, {
        "key": "555555555555555555",
        "value": "自阿斯蒂芬盒555555"
      }, {
        "key": "333333333333333333333",
        "value": "自阿斯蒂芬盒"
      }, {
        "key": "666666",
        "value": "666666ddddddddds的"
      }, {
        "key": "黑暗时代回复",
        "value": "撒扩大吉安弗兰"
      }, {
        "key": "啊快点放假奥尔",
        "value": "啊看到了放假啊滴哦"
      }]
      */


  valueObjArr: any [] = [];

  constructor() {
    super();
  }

  ngOnInit() {
    this.dealEntity();
  }

  dealEntity() {
    let $this = this;
    this.entity.valueArr = [];
    if (this.entity.value) {
      this.valueObjArr = JSON.parse(this.entity.value);
      $this.entity.valueArr =this.valueObjArr;
      console.log(this.entity)
    } else {
      $this.entity.valueArr = [];
    }
  }

  //json change begin  //whether any better solution
  changeValue(v,index) {
    this.entity.valueArr[index].value = v.value;
    this.valueObjArr[index] = v;
    this.entity.value = JSON.stringify(this.valueObjArr);
    this.validateForm.controls.value.setValue(this.entity.value);
    console.log(this.entity)
  }

  changeKey(v, index) {
    this.entity.valueArr[index].key = v.key;
    this.valueObjArr[index] = v;
    this.entity.value = JSON.stringify(this.valueObjArr);
    this.validateForm.controls.value.setValue(this.entity.value);
    console.log(this.entity)
  }

  remove(index) {
    this.valueObjArr.splice(index, 1);
    this.entity.valueArr =this.valueObjArr;
    this.entity.value = JSON.stringify(this.valueObjArr);
    this.validateForm.controls.value.setValue(this.entity.value);
    console.log(this.entity)
  }

  add() {
    this.valueObjArr.push({ 'key': '', 'value': '' });
    this.entity.value = JSON.stringify(this.valueObjArr);
    this.validateForm.controls.value.setValue(this.entity.value);
    console.log(this.entity)
  }

  //json change end
}
